package com.tzy.evaluation.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tzy.common.constant.CacheConstant;
import com.tzy.common.entity.UserLikes;
import com.tzy.evaluation.mapper.UserLikesMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户点赞表 服务实现类
 * </p>
 *
 * @author 谭同学
 * @since 2022-03-26
 */
@Service
@Slf4j
public class UserLikesService extends ServiceImpl<UserLikesMapper, UserLikes> implements IUserLikesService {
    @Resource
    private RedisService redisService;
    @Resource
    private UserLikesMapper userLikesMapper;

    public UserLikes getByLikedUserIdAndLikedPostId(int likedUserId, int likingUserId) {
        return userLikesMapper.findByLikedUserIdAndLikedPostId(likedUserId, likingUserId);
    }
    @Transactional
    public void transLikedFromRedis2DB() {
        List<UserLikes> list = redisService.getLikedDataFromRedis( );
        for (UserLikes like : list) {
            UserLikes userLikes = getByLikedUserIdAndLikedPostId(like.getLikedUserId(), like.getLikingUserId());
            if (userLikes == null) {
                log.info("没有记录，直接存入save(like);");
                //没有记录，直接存入save(like);
            } else {
                //有记录，需要更新
                log.info("有记录，需要更新");
                userLikes.setStatus(like.getStatus());
                save(userLikes);
            }
        }
    }

    /**
     * 点赞
     *
     * @param evaluationId
     * @param likedUserId
     * @param likingUserId
     */
    public boolean likeTheEvaluation(int evaluationId, int likedUserId, int likingUserId) {
        log.info("点赞数据存入redis开始，evaluationId:{}，likedUserId:{}，likingUserId:{}",
                evaluationId, likedUserId, likingUserId);
        synchronized (this) {
            /**
             * 只有未点赞的用户才可以进行点赞
             */
//            likeArticleLogicValidate(evaluationId, likedUserId, likingUserId);
            //1.用户总点赞数 +1
//            redisTemplate.opsForHash().increment(CacheConstant.EVALUATION_TOTAL_LIKED_COUNT +evaluationId, String.valueOf(likedUserId), 1);
            Long increment = redisService.increment(CacheConstant.EVALUATION_TOTAL_LIKED_COUNT + evaluationId);
            log.info("increment=" + increment);
            /**
             * 2.用户喜欢的评价设为 1 (已点赞)
             */
//            String userLikeResult = (String) redisTemplate.opsForHash().get(CacheConstant.LIKING_USER_ID +evaluationId, String.valueOf(likingUserId));
            Boolean setBit = redisService.setBit(CacheConstant.LIKING_USER_ID, evaluationId, true);
//            List<Integer> articleIdList = new ArrayList<>();
//            userLikeResult == null ? new ArrayList<Integer>() : FastjsonUtil.toList(userLikeResult, Long.class);
//            articleIdList.add(evaluationId);
//            redisTemplate.opsForHash().put(CacheConstant.LIKING_USER_ID, String.valueOf(likingUserId), FastjsonUtil.json2List(articleIdList));

            //3.评价点赞数+1
//            String articleLikedResult = (String) redisTemplate.opsForHash().get(CacheConstant.EVALUATION_LIKED_USER +evaluationId, String.valueOf(evaluationId));
//            List<Long> likePostIdSet = articleLikedResult == null ? new HashSet<Long>() : FastjsonUtil.toList(articleLikedResult, Long.class);
//            List<Integer> likePostIdSet = articleLikedResult == null ? new ArrayList<>() : FastjsonUtil.toList(articleLikedResult, Integer.class);
//            likePostIdSet.add(likingUserId);
//            redisTemplate.opsForHash().put(CacheConstant.EVALUATION_LIKED_USER +evaluationId, String.valueOf(evaluationId), FastjsonUtil.convertObjectToJSON(likePostIdSet));
//            log.info("取消点赞数据存入redis结束，evaluationId:{}，likedUserId:{}，likingUserId:{}", evaluationId, likedUserId, likingUserId);
            return setBit;
        }
    }

    public void setBit(String key, long offset, boolean bit) {
        redisService.setBit(key, offset, bit);
    }

    /**
     * 参数验证,只有未点赞的用户才可以进行点赞
     */
    UserLikes validateParam(int evaluationId, int userId) {
        QueryWrapper<UserLikes> queryWrapper = new QueryWrapper<>();

        return super.getOne(queryWrapper, false);
    }

    /**
     * 插入一条记录（选择字段，策略插入）
     *
     * @param entity 实体对象
     */
    @Override
    @Transactional
    @CacheEvict(allEntries = true)
    public boolean save(UserLikes entity) {
        return super.save(entity);
    }
}
